<template>
  <div id="map_container" style="width: 100%; height: 100%">
    <div id="map" class="map" style="width: 100%; height: 100%;"></div>
  </div>
</template>

<script setup lang="ts">
import Map from 'ol/Map';
import View from 'ol/View';
import Overlay from 'ol/Overlay';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';

import Style from 'ol/style/Style';
import {onMounted} from "vue";

/**
 * 创建一个用于浮动的窗口
 *
 * 这里需要复杂设计，每次点击浮动的时候，需要重新渲染内容
 *
 * @returns 浮动窗口
 */
const createPopover: HTMLElement = () => {
    const element = document.createElement('div');
    element.classList.add('float-bottom');
    element.classList.add('arrow-after-top');
    element.innerHTML = '<span>浮动窗口</span>';
    return element;
}

// 上一次点击的浮动窗口
let pre_overlay = undefined;
const popover = createPopover();

/**
 * 创建一个浮动层
 *
 * @param map -
 * @param position -
 * @param model -
 * @param zIndex -
 */
const createOverlay = (map, position, model, zIndex: number = 1) => {
    // create overlay
    const element = document.createElement('div');
    element.classList.add('sea-float-box');
    element.innerHTML = `<button class="el-button">${model}</button>`;
    const htmlOverlay = new Overlay({
        position: position,
        element: element,
        positioning: 'top-left'
    });
    map.addOverlay(htmlOverlay);

    // event
    element.addEventListener('click', () => {
        // 恢复上一次浮动层的 z-index
        if (pre_overlay !== undefined) {
            pre_overlay.parentElement.style.zIndex = 0;
        }

        // 记录浮动层，并切换气泡窗口的父级容器
        pre_overlay = element;
        element.appendChild(popover);

        // 重点是这一行代码
        element.parentElement.style.zIndex = zIndex;
    });
}

onMounted(() => {
    let map = new Map({
        view: new View({
            center: [12950000, 4860000],
            zoom: 4
        }),
        layers: [
            // 底图
            new TileLayer({
                source: new XYZ({url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}'})
            })
        ],
        target: 'map'
    });

    // 鼠标点击事件
    map.on('click', function (evt) {
        console.log(evt.pixel);
    });

    createOverlay(map, [12950000, 4860000], 'popover1', 1);
    createOverlay(map, [12950000, 4970000], 'popover2', 1);
})
</script>

<style>
.map {
    width: 100%;
    height: 400px;
}
</style>
